<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RichTextEditor from '@/components/RichTextEditor.vue'
import {
  fetchMoviesPage,
  getMoviesById,
  createMovies,
  updateMovies,
  deleteMovies,
  deleteMoviesBatch,
} from '@/api/movies'
import request from '@/utils/request'

const loading = ref(false)
const pageNo = ref(1)
const pageSize = ref(5)
const total = ref(0)
const list = ref([])

const query = reactive({ mname: '', type: '', status: '' })
const typeOptions = ['科幻', '动作', '动画', '剧情', '喜剧', '悬疑', '爱情', '冒险', '犯罪', '奇幻']

const multipleSelection = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增电影')
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  id: null,
  mname: '',
  type: '',
  mdate: '',
  mtime: 120,
  rating: 8.0,
  status: 'HOT',
  price: 50,
  posterUrl: '',
  imageUrl: '',
  description: '',
})

const rules = {
  mname: [{ required: true, message: '请输入片名', trigger: 'blur' }],
  type: [{ required: true, message: '请输入或选择类型', trigger: 'blur' }],
  mdate: [{ required: true, message: '请选择上映日期', trigger: 'change' }],
  mtime: [{ required: true, message: '请输入片长', trigger: 'blur' }],
  rating: [{ required: true, message: '请输入评分', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  price: [{ required: true, message: '请输入票价', trigger: 'blur' }],
  posterUrl: [{ required: true, message: '请上传图片链接', trigger: 'blur' }],
}

function loadData() {
  loading.value = true
  fetchMoviesPage({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    mname: query.mname || undefined,
    type: query.type || undefined,
    status: query.status || undefined,
  })
    .then((res) => {
      if (String(res.code) === '200') {
        list.value = res.data?.records || []
        total.value = res.data?.total || 0
      } else {
        ElMessage.error(res.msg || '查询失败')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function handleQuery() {
  pageNo.value = 1
  loadData()
}

function resetQuery() {
  query.mname = ''
  query.type = ''
  query.status = ''
  handleQuery()
}

function handleSelectionChange(rows) {
  multipleSelection.value = rows || []
}

function handleAdd() {
  dialogTitle.value = '新增电影'
  isEdit.value = false
  Object.assign(form, {
    id: null,
    mname: '',
    type: '',
    mdate: '',
    mtime: 120,
    rating: 8.0,
    status: 'HOT',
    price: 50,
    posterUrl: '',
    imageUrl: '',
    description: '',
  })
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑电影'
  isEdit.value = true
  const clone = { ...row }
  clone.rating = Number(clone.rating ?? 0)
  clone.price = Number(clone.price ?? 0)
  Object.assign(form, clone)
  dialogVisible.value = true
}

function submitForm() {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = { ...form }
      const api = isEdit.value ? updateMovies : createMovies
      const res = await api(payload)
      if (String(res.code) === '200') {
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
        dialogVisible.value = false
        loadData()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (e) { }
  })
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(`确认删除电影“${row.mname}”吗？`, '提示', { type: 'warning' })
    const res = await deleteMovies(row.id)
    if (String(res.code) === '200') {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) { }
}

async function handleBatchDelete() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return ElMessage.warning('请先选择要删除的记录')
  try {
    await ElMessageBox.confirm(`确认批量删除选中的 ${ids.length} 条记录吗？`, '提示', { type: 'warning' })
    const res = await deleteMoviesBatch(ids)
    if (String(res.code) === '200') {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) { }
}

function handleSizeChange(size) {
  pageSize.value = size
  pageNo.value = 1
  loadData()
}

function handleCurrentChange(page) {
  pageNo.value = page
  loadData()
}

function htmlToText(html) {
  if (!html) return ''
  const div = document.createElement('div')
  div.innerHTML = html
  return (div.textContent || div.innerText || '').trim()
}

// 图片上传相关
const coverInputRef = ref(null)
const coverUploading = ref(false)
function triggerCoverUpload() {
  coverInputRef.value?.click()
}
function handleCoverFileChange(e) {
  const file = e.target.files?.[0]
  if (file) uploadCover(file)
  e.target.value = ''
}
async function uploadCover(file) {
  coverUploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await request.post('/file/rich-text-image', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    if (String(res.code) === '200') {
      form.posterUrl = res.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res.msg || '上传失败')
    }
  } finally {
    coverUploading.value = false
  }
}

onMounted(loadData)
</script>

<template>
  <div class="page">
    <div class="page-header">
      <div class="title">电影管理</div>
      <div class="actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增电影
        </el-button>
        <el-button type="danger" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <el-card class="card" shadow="never">
      <el-form :inline="true" :model="query" class="query-form">
        <el-form-item label="片名">
          <el-input v-model="query.mname" placeholder="支持模糊查询" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="query.type" placeholder="全部" clearable style="width: 180px">
            <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable style="width: 180px">
            <el-option label="热映" value="HOT" />
            <el-option label="下架" value="OFFLINE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="card" shadow="never">
      <el-table :data="list" v-loading="loading" border @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="mname" label="片名" min-width="180" />
        <el-table-column prop="posterUrl" label="图片" min-width="155">
          <template #default="{ row }">
            <el-image v-if="row.posterUrl" :src="row.posterUrl" fit="cover"
              style="width: 130px; height: 132px; border-radius: 4px; border: 1px solid var(--el-border-color);"
              preview-teleported :preview-src-list="[row.posterUrl]" />
            <span v-else>-</span>
          </template>
        </el-table-column>F
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="mdate" label="上映日期" width="140" />
        <el-table-column prop="mtime" label="片长(分钟)" width="120" />
        <el-table-column prop="rating" label="评分" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'HOT' ? 'success' : 'info'">
              {{ row.status === 'HOT' ? '热映' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="票价" width="100">
          <template #default="{ row }">
            ￥{{ Number(row.price ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="posterUrl" label="海报" min-width="160">
          <template #default="{ row }">
            <a v-if="row.posterUrl" :href="row.posterUrl" target="_blank">打开链接</a>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="description" label="简介" min-width="220">
          <template #default="{ row }">
            <span class="desc">{{ htmlToText(row.description) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize" :current-page="pageNo" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="片名" prop="mname">
          <el-input v-model="form.mname" placeholder="请输入片名" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" filterable allow-create default-first-option style="width: 220px">
            <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="上映日期" prop="mdate">
          <el-date-picker v-model="form.mdate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="片长(分钟)" prop="mtime">
          <el-input-number v-model="form.mtime" :min="1" :step="10" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-input-number v-model="form.rating" :min="0" :max="10" :step="0.1" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width: 180px">
            <el-option label="热映" value="HOT" />
            <el-option label="下架" value="OFFLINE" />
          </el-select>
        </el-form-item>
        <el-form-item label="票价(元)" prop="price">
          <el-input-number v-model="form.price" :min="0" :step="0.5" />
        </el-form-item>
        <!-- <el-form-item label="海报链接" prop="posterUrl">
          <el-input v-model="form.posterUrl" placeholder="http(s)://..." />
        </el-form-item> -->
        <el-form-item label="电影图片" prop="posterUrl">
          <div class="image-upload-row">
            <el-image v-if="form.posterUrl" :src="form.posterUrl"
              style="width: 180px; height: 132px; margin-right: 12px; border-radius: 4px; border: 1px solid var(--el-border-color);" />
            <el-input v-model="form.posterUrl" placeholder="上传自动填充或粘贴完整地址">
              <template #append>
                <el-button :loading="coverUploading" @click="triggerCoverUpload">上传</el-button>
              </template>
            </el-input>
            <input ref="coverInputRef" type="file" accept="image/*" class="hidden-file"
              @change="handleCoverFileChange" />
          </div>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <RichTextEditor v-model="form.description" height="260px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.card {
  margin-bottom: 12px;
}

.query-form :deep(.el-form-item) {
  margin-right: 12px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.desc {
  display: inline-block;
  max-width: 380px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hidden-file {
  display: none;
}

.image-upload-row {
  display: flex;
  align-items: center;
}
</style>